﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WcfContrib.Extensions;
using WcfContrib.Exceptions;
using WcfContrib.Resources;
using System.ServiceModel;
using System.ServiceModel.Security;

namespace WcfContrib.Security
{
    /// <summary>
    /// Represents the base class for implementing authorization logic upon operation invocation.
    /// </summary>
    [AttributeUsage(AttributeTargets.Method)]
    public abstract class SecuredOperationCallAttribute : OperationCallActionAttribute
    {
        #region Abstract / Virtual Methods
        /// <summary>
        /// Returns the unauthorized exception to be thrown to the client.
        /// </summary>
        /// <returns>The exception</returns>
        protected virtual Exception GetUnauthorizedException()
        {
            return FaultExceptionBase.CreateAccessDeniedFault();
        }

        /// <summary>
        /// Returns whether or not the operation can be executed
        /// </summary>
        /// <param name="operationName">The operation name</param>
        /// <param name="inputs">The operation input parameters</param>
        /// <returns>Whether or not the operation can be executed</returns>
        protected virtual bool CanExecute(string operationName, object[] inputs)
        {
            return true;
        }
        #endregion
        
        /// <summary>
        /// Checks if the operation can be executed.
        /// If not, throws an unauthorized exception
        /// </summary>
        /// <param name="operationName">The operation name</param>
        /// <param name="inputs">The input parameters</param>
        /// <param name="context">The context that was returned from the context loading method</param>
        protected override void Execute(string operationName, object[] inputs, object context)
        {
            if (!CanExecute(operationName, inputs))
            {
                throw GetUnauthorizedException();
            }
        }
    }
}
